package com.zyx.javademo.nio.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/17 12:37
 * desc: FileChannel读取数据到buffer中
 */
public class FileChannelRead {
    public static void main(String[] args) {
        // 创建FileChannel
        try (RandomAccessFile raf = new RandomAccessFile("input/nio/read01.txt", "rw");
             FileChannel fileChannel = raf.getChannel()) {
            // 创建Buffer
            ByteBuffer buf = ByteBuffer.allocate(128);
            int bufRead;
            // 读取数据到buffer中
            while ((bufRead = fileChannel.read(buf)) != -1) {
                System.out.println("开始读取buffer中的内容...");

                buf.flip();
                while (buf.hasRemaining()) {
                    System.out.println((char) buf.get());
                }

                buf.clear();
            }

            System.out.println("buffer中数据已经读取完毕.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
